import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { InsertResult, Repository } from 'typeorm';
import { UserEntity } from './User.entity';
import { log } from 'winston';

@Injectable()
export class UserService {

  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {
  }

  async findOne(userId: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        id: userId,
      },
    });
    if (!user) {
      throw new Error('user not found');
    }
    return user;
  }

  async findOneByName(userName: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        userName: userName,
      },
    });
    if (!user) {
      throw new Error('user not found');
    }
    return user;
  }

  /**
   * 根据用户名和密码异步查找一个用户。
   *
   * @param payload 包含用户名和密码的对象
   * @returns 返回一个Promise，解析为UserEntity类型的用户实体。
   */
  async findOneByNameAndPassword(payload: any): Promise<UserEntity> {
    // 通过用户名查询用户
    const user = await this.userRepository.findOne({
      where: {
        userName: payload.userName,
      },
    });

    // 如果用户不存在，则抛出错误
    if (!user) {
      throw new Error('该用户不存在');
    } else if (user.userPassword !== payload.userPassword) {
      // 如果密码不匹配，则抛出错误
      throw new Error('密码错误');
    }

    return user;
  }


  async findAll(): Promise<UserEntity[]> {
    return await this.userRepository.find();
  }


  async addUser(user: UserEntity) {
    try {
      await this.userRepository.insert(user);
      return '插入成功';
    } catch (e) {
      throw new Error(e);
    }
  }
}
